<template>
  <el-dialog v-model="visible" :title="$t('nocaccount.add')" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
      label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="accountName" :label="$t('nocaccount.userName')" style="width: 400px;">
            <el-input v-model.trim="dataForm.accountName" :placeholder="$t('nocaccount.userName')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="companyPost" :label="$t('nocaccount.post')" style="width: 400px;">
            <el-select v-model="dataForm.companyPost" placeholder="请选择" clearable>
              <el-option label="销售" value="销售"></el-option>
              <el-option label="技术" value="技术"></el-option>
              <el-option label="采购" value="采购"></el-option>
              <el-option label="厂长" value="厂长"></el-option>
              <el-option label="总经理" value="总经理"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="mobilePhone" :label="$t('nocaccount.tel')" style="width: 400px;">
            <el-input v-model.trim="dataForm.mobilePhone" :placeholder="$t('nocaccount.tel')"></el-input>
<div class="rr-login-right-main-btn">
添加后使用此手机号登录微信小程序
              </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="verificationCode" :label="$t('nocaccount.verifyCode')" style="width: 400px;" >
            <el-space >
              <el-input v-model.trim="dataForm.verificationCode" :placeholder="$t('nocaccount.verifyCode')"  ></el-input>
              <el-button type="primary"
                :disabled="state.countdown > 0"
                @click="getCheckCode"
              >
                {{ state.countdown > 0 ? `${state.countdown}秒后重试` : '获取验证码' }}
              </el-button>
            </el-space>
          </el-form-item>
        </el-col>

      </el-row>

    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted,onBeforeUnmount, reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { isEmail, isMobile } from "@/utils/utils";
import { IObject } from "@/types/interface";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const roleList = ref<any[]>([]);
const taskleader = ref([] as any[]);
const postList = ref<any[]>([]);
const dataFormRef = ref();
declare const TencentCaptcha: any;

const state = reactive({
  captchaUrl: "",
  loading: false,
  year: new Date().getFullYear(),
  countdown: 0,
  timer: null as any
});

const dataForm = reactive({
  skillGroupId: "",
  userId: null,
  accountName: "",
  companyPost: "",
  mobilePhone: "",
  verificationCode: ""
});

// 获取验证码方法
const getCheckCode = () => {
  if (!dataForm.mobilePhone) {
    ElMessage.warning('请输入手机号或邮箱');
    return;
  }
  try {
    let captcha =  new TencentCaptcha("194163642", (res:any)=>{
      if (res.ret === 0) {
        startCountdown();
        baseService.post(`/h5/testDescribeCaptchaResult`,{
          randstr: res.randstr,
          ticket: res.ticket,
          phone:dataForm.mobilePhone,
        }).then(res=>{
          if (res.code == 0 && res.CaptchaCode == 1){
            ElMessage.success("发送验证码成功")
          }else{
            ElMessage.error("验证失败")
          }
        })
      }
    });
    captcha.show();
  } catch(err:any) {
    ElMessage.error('验证码发送失败');
  }

};



const rules = ref({
  accountName: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  companyPost: [{ required: true, message: t("validate.required"), trigger: "change" }],
  mobilePhone: [{
    required: true,
    trigger: ['blur', 'change'],
    validator: (_rule: any, value: any, callback: any) => {
      if (!value || String(value).trim().length === 0) {
        callback(new Error(t('validate.required')));
      } else {
        callback();
      }
    }
  }],
  verificationCode: [{
    required: true,
    trigger: ['blur', 'change'],
    validator: (_rule: any, value: any, callback: any) => {
      if (!value || String(value).trim().length === 0) {
        callback(new Error(t('validate.required')));
      } else {
        callback();
      }
    }
  }],
});

const init = () => {
  visible.value = true;
  dataForm.userId = null;
  // 打开弹窗时清理上次的校验状态，避免误报
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
};


// 开始倒计时
const startCountdown = () => {
  state.countdown = 60;
  state.timer = setInterval(() => {
    state.countdown--;
    if (state.countdown <= 0 && state.timer) {
      clearInterval(state.timer);
      state.timer = null;
    }
  }, 1000);
};

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  if (state.timer) {
    clearInterval(state.timer);
    state.timer = null;
  }
});


// 获取信息
const getInfo = (userId: number) => {
  baseService.get(`/sys/user/${userId}`).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
   console.log('表单数据:', dataForm);
      console.log('校验结果:', valid);
    if (!valid) {
    console.log('校验结果:--------------', valid);
      return false;
    }
    (baseService.post)("/sys/user/saveExhibitionSubAccount", {
    ...dataForm,
    }).then(() => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>

<style lang="less" scoped>
.mod-sys__user {
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}

.el-form-item::v-deep {
  .el-checkbox-group {
    .el-checkbox {
      width: 120px;
    }
  }
}

.rr-login-right-main-btn {
  color: #606266;
  font-size: 12px;
  margin-top: 8px;
  padding-left: 0px;
  line-height: 1.4;
  font-weight: bold; // 添加加粗属性
}
</style>
